package com.qxzn.app.personalcenter.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.api.util.EventBusManager;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.BindRobotBean;
import com.qxzn.app.bean.EventBusBean;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.page.activity.QrScanActivity;
import com.qxzn.app.page.view.MyDialog;
import com.qxzn.app.personalcenter.R;
import com.qxzn.app.personalcenter.R2;
import com.qxzn.app.util.ActivityStack;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 添加机器人(机器码：9ac019acab486ad7db721f2b6f1b94a8)
 */
public class AddRobotActivity extends BaseActivity {
    @BindView(R2.id.iv_robot)
    ImageView ivRobot;
    @BindView(R2.id.tv_guide)
    TextView tvGuide;
    @BindView(R2.id.tv_bind)
    TextView tvBind;
    private String btn_text;
    private StringBuilder promptInfo;
    private MyDialog dialog;

    @Override
    protected int initLayout() {
        return R.layout.activity_add_robot;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void iniTitleBar() {
        tv_title.setText("添加机器人");
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        btn_text = getIntent().getStringExtra("btn_text");
        tvGuide.setText(getIntent().getStringExtra("prompt_info"));
        tvBind.setText(btn_text);
    }

    @OnClick(R2.id.tv_bind)
    public void onViewClicked() {
        if ("已开机".equals(btn_text)) {
            startActivityForResult(new Intent(this, QrScanActivity.class), 1);
        } else if ("立即绑定".equals(btn_text)) {
            bingDevice(getIntent().getStringExtra("deviceId"));
        } else if ("返回首页".equals(btn_text)) {
            ActivityStack.finishAllWithoutActivity("com.qxzn.app.desktoprobot.MainActivity");
        } else if ("再次扫码".equals(btn_text)) {
//            List<String> list = new ArrayList<>();
//            list.add("MainActivity");
//            list.add("PersonalCenterActivity");
//            ActivityStack.finishAllWithoutActivity(list);
            startActivityForResult(new Intent(this, QrScanActivity.class), 1);
            EventBusManager.post(new EventBusBean.Builder().id(1).build());
        }
    }

    @Override
    public void onEventBus(EventBusBean busBean) {
        super.onEventBus(busBean);
        if (busBean.getId() == 1) {
            finish();
        }
    }

    private void bingDevice(String deviceId) {
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), String.format("{\"device_id\":\"%s\"}", deviceId));
        Call<BaseBean<BindRobotBean>> call = HttpRequest.getService().bingDevice(body);
        call.enqueue(new Callback<BaseBean<BindRobotBean>>() {
            @Override
            public void onResponse(Call<BaseBean<BindRobotBean>> call, Response<BaseBean<BindRobotBean>> response) {
                if (response.body() != null && response.body().getCode() == 200) {
                    Intent intent = new Intent(AddRobotActivity.this, AddRobotActivity.class);
                    intent.putExtra("prompt_info", "绑定成功！10秒后自动返回首页！");
                    intent.putExtra("btn_text", "返回首页");
                    startActivity(intent);
                    return;
                } else if (response.body() != null && (response.body().getCode() == 403 || response.body().getCode() == 500)) {
                    showAuthDialog(response.body().getMsg());
                    return;
                } else {
                    if (response.body() != null && !TextUtils.isEmpty(response.body().getMsg())) {
                        Intent intent = new Intent(AddRobotActivity.this, AddRobotActivity.class);
                        intent.putExtra("prompt_info", response.body().getMsg());
                        intent.putExtra("btn_text", "再次扫码");
                        startActivity(intent);
                        return;
                    }
                }
                Intent intent = new Intent(AddRobotActivity.this, AddRobotActivity.class);
                intent.putExtra("prompt_info", "绑定失败咯！");
                intent.putExtra("btn_text", "再次扫码");
                startActivity(intent);
            }

            @Override
            public void onFailure(Call<BaseBean<BindRobotBean>> call, Throwable t) {
                Intent intent = new Intent(AddRobotActivity.this, AddRobotActivity.class);
                intent.putExtra("prompt_info", "绑定失败咯！");
                intent.putExtra("btn_text", "再次扫码");
                startActivity(intent);
            }
        });
    }

    private void showAuthDialog(String msg) {
        if (dialog == null) {
            View layout = LayoutInflater.from(AddRobotActivity.this).inflate(R.layout.dialog_admin_confirm, null);
            TextView tv_message = layout.findViewById(R.id.tv_message);
            ImageView iv_close = layout.findViewById(R.id.iv_close);
            dialog = new MyDialog.Builder(AddRobotActivity.this).setContentView(layout).setCancelAble(false).setCanceledOnTouchOutside(false).createCustomDialog();
            if (TextUtils.isEmpty(msg)) {
                tv_message.setText("绑定需求已发出，待管理员确认");
            } else {
                tv_message.setText(msg);
            }
            iv_close.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    ActivityStack.finishAllWithoutActivity("com.qxzn.app.desktoprobot.MainActivity");
                }
            });
        }
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                String scan_result = data.getStringExtra("scan_result");
                if (!TextUtils.isEmpty(scan_result)) {
                    promptInfo = new StringBuilder();
                    promptInfo.append("嘻嘻！小π");
                    promptInfo.append(scan_result);
                    promptInfo.append("来啦\n");
                    promptInfo.append("主人是你吗！");
                    Intent intent = new Intent(this, AddRobotActivity.class);
                    intent.putExtra("prompt_info", promptInfo.toString());
                    intent.putExtra("btn_text", "立即绑定");
                    intent.putExtra("deviceId", scan_result);
                    startActivity(intent);
                }
            }
        }
    }
}
